package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.constant.DubboMethodConstant;
import cc.rengu.igas.bomp.common.dao.MchntApexInfoMapper;
import cc.rengu.igas.bomp.common.dao.MchntImageInfoMapper;
import cc.rengu.igas.bomp.common.dao.WechatMchntInfoMapper;
import cc.rengu.igas.bomp.common.dao.impl.MchntApexInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntImageInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.WechatMchntInfoMapperImpl;
import cc.rengu.igas.bomp.common.entity.MchntApexInfo;
import cc.rengu.igas.bomp.common.entity.MchntBaseInfo;
import cc.rengu.igas.bomp.common.entity.MchntImageInfo;
import cc.rengu.igas.bomp.common.entity.WechatMchntInfo;
import cc.rengu.igas.bomp.common.enums.*;
import cc.rengu.igas.bomp.common.util.InitParamUtil;
import cc.rengu.igas.bomp.core.realize.MchntImageUnifiedService;
import cc.rengu.igas.bomp.core.realize.NormalMchntInfoService;
import cc.rengu.igas.bomp.core.realize.impl.MchntImageUnifiedServiceImpl;
import cc.rengu.igas.bomp.core.realize.impl.NormalMchntInfoServiceImpl;
import cc.rengu.igas.bomp.core.service.base.ManageService;
import cc.rengu.igas.bomp.facade.bean.ImageInfoBean;
import cc.rengu.igas.bomp.facade.bean.MchntApexInfoBean;
import cc.rengu.igas.bomp.facade.bean.MchntImageInfoBean;
import cc.rengu.igas.bomp.facade.request.WeChatActivityRateModifyRequest;
import cc.rengu.igas.bomp.facade.response.WeChatActivityRateModifyResponse;
import cc.rengu.igas.channel.wechat.facade.base.Header;
import cc.rengu.igas.channel.wechat.facade.bean.ActivityAdditionalInfo;
import cc.rengu.igas.channel.wechat.facade.bean.ActivityApplyInfo;
import cc.rengu.igas.channel.wechat.facade.bean.ActivityDetailModifyInfo;
import cc.rengu.igas.channel.wechat.facade.request.ActivityRegistInfoModifyRequest;
import cc.rengu.igas.channel.wechat.facade.response.ActivityRegistInfoModifyResponse;
import cc.rengu.igas.channel.wechat.facade.result.Result;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.*;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 修改微信费率优惠活动申请单信息
 *
 * @version 1.0
 * @date 2019/08/15
 */
public class WeChatActivityRateModifyService extends ManageService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        WeChatActivityRateModifyRequest weChatActivityRateModifyRequest = new WeChatActivityRateModifyRequest();
        ConvertUtil.convertOutput(weChatActivityRateModifyRequest);
        return weChatActivityRateModifyRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        WeChatActivityRateModifyRequest weChatActivityRateModifyRequest = (WeChatActivityRateModifyRequest) request;
        WeChatActivityRateModifyResponse weChatActivityRateModifyResponse = new WeChatActivityRateModifyResponse();
        BizResponse<WeChatActivityRateModifyResponse> bizResponse = new BizResponse<>();
        bizResponse.setResult(weChatActivityRateModifyResponse);
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        weChatActivityRateModifyResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        weChatActivityRateModifyResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        NormalMchntInfoService normalMchntInfoService = new NormalMchntInfoServiceImpl();
        MchntBaseInfo mchntBaseInfo = normalMchntInfoService.checkMchntStatus(weChatActivityRateModifyRequest.getHeader().getInstId(), weChatActivityRateModifyRequest.getMchntNo());
        //先置为非正式，用于将数据直接入库
        mchntBaseInfo.setMchntStatus(MchntStatusEnum.UNNORMAL.getStatus());

        WechatMchntInfoMapper wechatMchntInfoMapper = new WechatMchntInfoMapperImpl();
        WechatMchntInfo wechatMchntInfo = wechatMchntInfoMapper.selectWechatMchntInfoByPrimaryKey(mchntBaseInfo.getInstId(), mchntBaseInfo.getMchntNo());
        if (null == wechatMchntInfo) {
            rglog.error("无微信商户信息.");
            throw new BizException(RespCodeEnum.WECHAT_ACTIVITY_RATE_ERROR.getRespCode(), "无微信产品信息");
        }
        if (StringUtil.isEmptyOrNull(wechatMchntInfo.getWechatMchntNo())) {
            rglog.error("未微信进件.");
            throw new BizException(RespCodeEnum.WECHAT_ACTIVITY_RATE_ERROR.getRespCode(), "未微信进件");
        }
        if (!AppParamConstant.YES.equals(wechatMchntInfo.getRealNameFlag())) {
            rglog.error("未微信实名认证.");
            throw new BizException(RespCodeEnum.WECHAT_ACTIVITY_RATE_ERROR.getRespCode(), "未微信实名认证");
        }

        imageUpToWechat(weChatActivityRateModifyRequest, mchntBaseInfo, wechatMchntInfo);

        ActivityRegistInfoModifyRequest activityRegistInfoModifyRequest = initActivityRegistInfoModifyRequest(weChatActivityRateModifyRequest, mchntBaseInfo, wechatMchntInfo);
        DubboService dubboService = new DubboServiceImpl();
        Result result = (Result) dubboService.callDubboService(DubboMethodConstant.DUBBO_WECHAT_MCHNT_SERVICE, "activityRegistInfoModify", activityRegistInfoModifyRequest);
        if (null == result || !result.isSuccess() || null == result.getResult()) {
            rglog.error("服务调用失败.");
            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
        }

        ActivityRegistInfoModifyResponse activityRegistInfoModifyResponse = (ActivityRegistInfoModifyResponse) result.getResult();
        if (!DubboMethodConstant.DUBBO_SUCCESS.equals(activityRegistInfoModifyResponse.getRespCode())) {
            rglog.error("调用服务失败<{}>-<{}>", activityRegistInfoModifyResponse.getRespCode(), activityRegistInfoModifyResponse.getRespDesc());
            throw new BizException(activityRegistInfoModifyResponse.getRespCode(), activityRegistInfoModifyResponse.getRespDesc());
        }
        if (StringUtil.isEmptyOrNull(activityRegistInfoModifyResponse.getApplicationId())) {
            rglog.error("微信未返回申请单编号.");
            throw new BizException(RespCodeEnum.WECHAT_ACTIVITY_RATE_ERROR.getRespCode(), "微信未返回申请单编号");
        }
        /*保存申请单号*/
        List<MchntApexInfoBean> mchntApexInfoBeanList = new ArrayList<>();
        MchntApexInfoBean wApplicationIdMchntApexInfoBean = new MchntApexInfoBean();
        mchntApexInfoBeanList.add(wApplicationIdMchntApexInfoBean);
        wApplicationIdMchntApexInfoBean.setPropertyKey(MchntApexPropeytyEnum.APPLICATION_ID.getPropertyKey());
        wApplicationIdMchntApexInfoBean.setPropertyValue(activityRegistInfoModifyResponse.getApplicationId());

        /*申请单状态*/
        MchntApexInfoBean wActivityStatusMchntApexInfomBean = new MchntApexInfoBean();
        mchntApexInfoBeanList.add(wActivityStatusMchntApexInfomBean);
        wActivityStatusMchntApexInfomBean.setPropertyKey(MchntApexPropeytyEnum.ACTIVITY_STATUS.getPropertyKey());
        wActivityStatusMchntApexInfomBean.setPropertyValue(WechatActivityStatusEnum.APPLICATION_STATE_AUDITING.getEpayStatus());

        /** 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MCMP_POOL_NAME);
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();
        try {
            InitParamUtil.savemchntApexInfo(mchntBaseInfo, mchntApexInfoBeanList);

            /**提交事务*/
            dbsUtil.dbsEndTransaction(true);
        } catch (Exception e) {
            rglog.error(cc.rengu.utility.base.StringUtil.ExceptionToString(e));
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.SYSTEM_BUSYNESS.getRespCode(), RespCodeEnum.SYSTEM_BUSYNESS.getRespDesc());
        }

        weChatActivityRateModifyResponse.setApplicationId(activityRegistInfoModifyResponse.getApplicationId());
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        WeChatActivityRateModifyResponse weChatActivityRateModifyResponse = (WeChatActivityRateModifyResponse) bizResponse.getResult();
        ConvertUtil.convertInput(weChatActivityRateModifyResponse);
    }


    /**
     * 图片上传微信
     */
    private void imageUpToWechat(WeChatActivityRateModifyRequest weChatActivityRateModifyRequest, MchntBaseInfo mchntBaseInfo, WechatMchntInfo wechatMchntInfo) throws Exception {
        MchntImageInfoMapper mchntImageInfoMapper = new MchntImageInfoMapperImpl();
        List<MchntImageInfo> mchntImageInfoList = mchntImageInfoMapper.selectMchntImageInfoByMchntNo(mchntBaseInfo.getInstId(), mchntBaseInfo.getMchntNo());
        if (CollectionUtils.isEmpty(mchntImageInfoList)) {
            mchntImageInfoList = new ArrayList<>();
        }

        String imageBasePath;
        SysParam imagePathSysParam = SysParamEnum.getSysParam(mchntBaseInfo.getInstId(), SysParamEnum.localStorageRootPath);
        if (null != imagePathSysParam && AppParamConstant.YES.equals(imagePathSysParam.getParamStatus())) {
            imageBasePath = imagePathSysParam.getParamValue() + File.separator;
            // imageBasePath = imagePathSysParam.getParamValue() + "/";
        } else {
            throw new BizException(RespCodeEnum.SYSTEM_BUSYNESS.getRespCode(), RespCodeEnum.SYSTEM_BUSYNESS.getRespDesc());
        }

        MchntImageUnifiedService mchntImageUnifiedService = new MchntImageUnifiedServiceImpl();
        for (MchntImageInfoBean mchntImageInfoBean : weChatActivityRateModifyRequest.getMchntImageInfoBeanList()) {
            for (ImageInfoBean imageInfoBean : mchntImageInfoBean.getImageInfoList()) {
                List<MchntImageInfo> mchntImageInfoOneList = mchntImageInfoList.stream().filter(item ->
                        mchntImageInfoBean.getImageType().equals(item.getImageType()) && imageInfoBean.getImageIndex().equals(String.valueOf(item.getImageIndex()))).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(mchntImageInfoOneList) && !StringUtil.isEmptyOrNull(mchntImageInfoOneList.get(0).getImageLocalPath())
                        && new String(Base64.decodeBase64(imageInfoBean.getImageLocalPath())).equals(mchntImageInfoOneList.get(0).getImageLocalPath())) {
                    rglog.info("影像<{}>序号<{}>未修改,使用原微信图片ID<{}>", mchntImageInfoOneList.get(0).getImageType(), mchntImageInfoOneList.get(0).getImageIndex(), mchntImageInfoOneList.get(0).getWechatMediaId());
                    imageInfoBean.setWechatImageId(mchntImageInfoOneList.get(0).getWechatMediaId());
                } else {
                    String mediaId = mchntImageUnifiedService.uploadToWechat(mchntBaseInfo, wechatMchntInfo, imageBasePath + new String(Base64.decodeBase64(imageInfoBean.getImageLocalPath())));
                    imageInfoBean.setWechatImageId(mediaId);
                }
            }
        }
    }

    /**
     * 初始化活动报名请求参数
     */
    private ActivityRegistInfoModifyRequest initActivityRegistInfoModifyRequest(WeChatActivityRateModifyRequest weChatActivityRateModifyRequest,
                                                                                MchntBaseInfo mchntBaseInfo, WechatMchntInfo wechatMchntInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);

        ActivityRegistInfoModifyRequest activityRegistInfoModifyRequest = new ActivityRegistInfoModifyRequest();
        Header header = InitParamUtil.initWechatHeader("actvreginfmodfy", mchntBaseInfo.getInstId(), sysSeqNum);
        activityRegistInfoModifyRequest.setHeader(header);
        activityRegistInfoModifyRequest.setChannelId(ChannelEnum.WXZF.getChannelType());
        activityRegistInfoModifyRequest.setThirdMchntNo(wechatMchntInfo.getWechatMchntNo());
        activityRegistInfoModifyRequest.setChannelType(wechatMchntInfo.getDstChannelType());

        MchntApexInfoMapper mchntApexInfoMapper = new MchntApexInfoMapperImpl();
        MchntApexInfo mchntApexInfo = mchntApexInfoMapper.selectMchntApexInfoByPrimaryKey(mchntBaseInfo.getInstId(), mchntBaseInfo.getMchntNo(), MchntApexPropeytyEnum.APPLICATION_ID.getPropertyKey());
        if (null == mchntApexInfo) {
            rglog.error("无活动申请编号.");
            throw new BizException(RespCodeEnum.WECHAT_ACTIVITY_RATE_ERROR.getRespCode(), "无活动申请编号");
        }
        activityRegistInfoModifyRequest.setApplicationId(mchntApexInfo.getPropertyValue());

        ActivityDetailModifyInfo ActivityDetailModifyInfo = initActivityDetailModifyInfo(weChatActivityRateModifyRequest, mchntBaseInfo);
        activityRegistInfoModifyRequest.setActivityDetailModifyInfo(ActivityDetailModifyInfo);

        ActivityAdditionalInfo activityAdditionalInfo = initActivityAdditionalInfo(weChatActivityRateModifyRequest);
        activityRegistInfoModifyRequest.setActivityAdditionalInfo(activityAdditionalInfo);

        return activityRegistInfoModifyRequest;
    }

    private ActivityDetailModifyInfo initActivityDetailModifyInfo(WeChatActivityRateModifyRequest weChatActivityRateModifyRequest, MchntBaseInfo mchntBaseInfo) throws Exception {
        ActivityDetailModifyInfo activityDetailModifyInfo = new ActivityDetailModifyInfo();
        // List<MchntSysParamBean> activityIdMchntSysParamBeanList = weChatActivityRateModifyRequest.getMchntSysParamBeanList()
        //         .stream().filter(item -> MchntSysParamEnum.WECHAT_ACTIVITY_ID.getParamKey().equals(item.getParamKey())).collect(Collectors.toList());
        // if (CollectionUtils.isEmpty(activityIdMchntSysParamBeanList)) {
        //     rglog.error("未上传活动ID.");
        //     throw new BizException(RespCodeEnum.WECHAT_ACTIVITY_RATE_ERROR.getRespCode(), "未上传活动ID");
        // }
        // String activityId = activityIdMchntSysParamBeanList.get(0).getParamVal();
        // activityDetailModifyInfo.setActivityId(activityId);

        MchntApexInfoMapper mchntApexInfoMapper = new MchntApexInfoMapperImpl();
        MchntApexInfo mchntApexInfo = mchntApexInfoMapper.selectMchntApexInfoByPrimaryKey(mchntBaseInfo.getInstId(), mchntBaseInfo.getMchntNo(), MchntApexPropeytyEnum.WECHAT_ACTIVITY_ID.getPropertyKey());
        if (null == mchntApexInfo) {
            rglog.error("无活动编号.");
            throw new BizException(RespCodeEnum.WECHAT_ACTIVITY_RATE_ERROR.getRespCode(), "无活动编号");
        }
        SysParam sysParam = SysParamEnum.getSysParam(mchntBaseInfo.getInstId(), mchntApexInfo.getPropertyValue(), SysParamEnum.ACTIVITY_RATE.getParamKey());
        if (null == sysParam) {
            rglog.error("未配置活动<{}>费率.", mchntApexInfo.getPropertyValue());
            throw new BizException(RespCodeEnum.WECHAT_ACTIVITY_RATE_ERROR.getRespCode(), "未配置活动费率");
        }
        activityDetailModifyInfo.setActivityRate(sysParam.getParamValue());

        List<ActivityApplyInfo> activityApplyInfoList = initActivityApplyInfoList(weChatActivityRateModifyRequest);
        activityDetailModifyInfo.setActivityApplyInfoList(activityApplyInfoList);

        return activityDetailModifyInfo;
    }

    private List<ActivityApplyInfo> initActivityApplyInfoList(WeChatActivityRateModifyRequest weChatActivityRateModifyRequest) {
        List<ActivityApplyInfo> activityApplyInfoList = new ArrayList<>();
        List<MchntImageInfoBean> activityMchntImageInfoBeanList = weChatActivityRateModifyRequest.getMchntImageInfoBeanList().stream().filter(item ->
                !ImageTypeEnum.ADDITIONAL_MATERIAL.getImageType().equals(item.getImageType())).collect(Collectors.toList());
        for (MchntImageInfoBean mchntImageInfoBean : activityMchntImageInfoBeanList) {
            ActivityApplyInfo activityApplyInfo = new ActivityApplyInfo();
            String wechatImageType = WechatImageTypeEnum.getWechatImageType(mchntImageInfoBean.getImageType());
            activityApplyInfo.setApplyMaterialId(wechatImageType);
            List<String> applyMaterialInfo = new ArrayList<>();
            activityApplyInfo.setApplyMaterialInfo(applyMaterialInfo);
            for (ImageInfoBean imageInfoBean : mchntImageInfoBean.getImageInfoList()) {
                applyMaterialInfo.add(imageInfoBean.getWechatImageId());
            }
            activityApplyInfoList.add(activityApplyInfo);
        }
        return activityApplyInfoList;
    }

    private ActivityAdditionalInfo initActivityAdditionalInfo(WeChatActivityRateModifyRequest weChatActivityRateModifyRequest) {
        ActivityAdditionalInfo activityAdditionalInfo = new ActivityAdditionalInfo();
        List<MchntApexInfoBean> additionalMchntSysParamBeanList = weChatActivityRateModifyRequest.getMchntApexInfoBeanList()
                .stream().filter(item -> MchntApexPropeytyEnum.ADDITIONAL_MSG.getPropertyKey().equals(item.getPropertyKey())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(additionalMchntSysParamBeanList)) {
            activityAdditionalInfo.setAddtionalMessage(additionalMchntSysParamBeanList.get(0).getPropertyValue());
        }

        List<MchntImageInfoBean> additionImageInfoBeanList = weChatActivityRateModifyRequest.getMchntImageInfoBeanList().stream().filter(item ->
                ImageTypeEnum.ADDITIONAL_MATERIAL.getImageType().equals(item.getImageType())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(additionImageInfoBeanList)) {
            if (!CollectionUtils.isEmpty(additionImageInfoBeanList.get(0).getImageInfoList())) {
                List<String> addtionalMaterial = new ArrayList<>();
                activityAdditionalInfo.setAddtionalMaterial(addtionalMaterial);
                for (ImageInfoBean imageInfoBean : additionImageInfoBeanList.get(0).getImageInfoList()) {
                    addtionalMaterial.add(imageInfoBean.getWechatImageId());
                }
            }
        }
        return activityAdditionalInfo;
    }

}
